package com.own.business.sync.trigger.base.method;

import com.alibaba.fastjson2.JSON;
import com.own.business.sync.trigger.base.common.TypeConstant;
import com.own.business.sync.trigger.base.config.SyncTriggerPollingCondition;
import com.own.business.sync.trigger.base.entity.SyncTrigger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 * ResolveMethod
 *
 * @author chenxueli
 * @date 2024-01-08 15:45:37
 */
@Slf4j
@Component
@Conditional(SyncTriggerPollingCondition.class)
public class ResolveMethodSpringHook {

    private static final Map<String, ResolveMethod> METHOD_MAP = new HashMap<>();
    @Resource
    private List<ResolveMethod> resolveMethodList;

    @PostConstruct
    private void init() {
        for (var service : resolveMethodList) {
            if (service.enable()) {
                METHOD_MAP.put(service.name(), service);
            }
        }
        if (!METHOD_MAP.isEmpty()) {
            // debug日志输出
            log.info("处理模板类型【{}】完成注册", JSON.toJSONString(METHOD_MAP.keySet()));
        }
    }

    /**
     * 获取处理方法
     *
     * @param name 名称
     * @return 处理方法
     */
    public ResolveMethod getMethod(String name) {
        return METHOD_MAP.get(name);
    }

    /**
     * 获取处理方法
     *
     * @param type   类型
     * @param method 处理方法
     * @return 处理方法
     */
    public Consumer<SyncTrigger> getMethod(int type, ResolveMethod method) {
        if (method == null) {
            return null;
        }
        return switch (type) {
            case TypeConstant.INSERT -> method::add;
            case TypeConstant.UPDATE -> method::update;
            case TypeConstant.DELETE -> method::delete;
            default -> null;
        };
    }

    /**
     * 获取处理方法
     *
     * @param type 类型
     * @param name 名称
     * @return 处理方法
     */
    public Consumer<SyncTrigger> getMethod(int type, String name) {
        var method = getMethod(name);
        return getMethod(type, method);
    }

}
